package com.qingyun.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.core.mybatisplus.core.ServicePlusImpl;
import com.qingyun.common.core.page.PagePlus;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.*;
import com.qingyun.shop.domain.bo.TiktokActivityBo;
import com.qingyun.shop.domain.vo.TiktokActivityVo;
import com.qingyun.shop.mapper.TiktokActivityMapper;
import com.qingyun.shop.mapper.TiktokActivityTagMapper;
import com.qingyun.shop.mapper.TiktokCouponMapper;
import com.qingyun.shop.service.ITiktokActivityService;
import com.qingyun.shop.service.ITiktokActivityToCouponService;
import com.qingyun.shop.service.ITiktokShopService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 优惠券活动Service业务层处理
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Service
@AllArgsConstructor
public class TiktokActivityServiceImpl extends ServicePlusImpl<TiktokActivityMapper, TiktokActivity, TiktokActivityVo> implements ITiktokActivityService {

	private ITiktokActivityToCouponService tiktokActivityToCouponService;

	private ITiktokShopService shopService;

	private final TiktokActivityTagMapper activityTagMapper;

	private final TiktokCouponMapper couponMapper;

    @Override
    public TiktokActivityVo queryById(Long id){
		if (!SecurityUtils.isManager()) {
			if (count(Wrappers.lambdaQuery(TiktokActivity.class)
				.eq(TiktokActivity::getShopId, SecurityUtils.getShop().getId())
				.eq(TiktokActivity::getId,id))==0) {
				throw new ServiceException("不能查询他人优惠卷信息");
			}
		}
		TiktokActivityVo tiktokActivityVo = getVoById(id);
		List<TiktokActivityToCoupon> list = tiktokActivityToCouponService.list(Wrappers.lambdaQuery(TiktokActivityToCoupon.class)
			.eq(TiktokActivityToCoupon::getActivityId, tiktokActivityVo.getId()));
		tiktokActivityVo.setCouponIds(list.stream().map((coupon->coupon.getCouponId())).collect(Collectors.toList()));

		List<Long> tagIds = activityTagMapper.selectList(Wrappers.query(new TiktokActivityTag().setActivityId(id))).stream().map(TiktokActivityTag::getTagId).collect(Collectors.toList());
		tiktokActivityVo.setTags(tagIds);

		return tiktokActivityVo;
    }

    @Override
    public TableDataInfo<TiktokActivityVo> queryPageList(TiktokActivityBo bo) {
    	if(!SecurityUtils.isManager()){
			bo.setShopId(SecurityUtils.getShop().getId());
		}
        PagePlus<TiktokActivity, TiktokActivityVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TiktokActivityVo> queryList(TiktokActivityBo bo) {
		if(!SecurityUtils.isManager()){
			bo.setShopId(SecurityUtils.getShop().getId());
		}
		return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<TiktokActivity> buildQueryWrapper(TiktokActivityBo bo) {
        LambdaQueryWrapper<TiktokActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), TiktokActivity::getTitle, bo.getTitle());
        lqw.eq(bo.getBeginDate() != null, TiktokActivity::getBeginDate, bo.getBeginDate());
        lqw.eq(bo.getEndDate() != null, TiktokActivity::getEndDate, bo.getEndDate());
        lqw.eq(StringUtils.isNotBlank(bo.getActityType()), TiktokActivity::getActityType, bo.getActityType());
        lqw.eq(bo.getShopId() != null, TiktokActivity::getShopId, bo.getShopId());
        lqw.like(bo.getShopName()!=null, TiktokActivity::getShopName,bo.getShopName());
        lqw.eq(bo.getStatus()!=null,TiktokActivity::getStatus,bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoTitle()), TiktokActivity::getVideoTitle, bo.getVideoTitle());
        return lqw;
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(TiktokActivityBo bo) {
		List<Long> couponIds = bo.getCouponIds();
		TiktokActivity add = BeanUtil.toBean(bo, TiktokActivity.class);
		if(!SecurityUtils.isManager()){
			add.setShopId(SecurityUtils.getShop().getId());
		}
		if (add.getShopId()==null) {
			throw new CustomException("商户id不能为空");
		}

		TiktokShop shop = shopService.getById(add.getShopId());
		if (ObjectUtil.isNull(shop)) {
			throw new CustomException("商户不存在");
		}
		add.setShopName(shop.getName());
		validEntityBeforeSave(bo);
		boolean save = save(add);
		if(save) {
			if(CollectionUtil.isNotEmpty(couponIds)) {
				couponIds.forEach(couponId -> {
					TiktokActivityToCoupon tiktokActivityToCoupon = new TiktokActivityToCoupon().setActivityId(add.getId()).setCouponId(couponId);
					tiktokActivityToCouponService.save(tiktokActivityToCoupon);
				});
				if (bo.getIsSynchronizationCoupon() != null && bo.getIsSynchronizationCoupon() == 1) {
					couponIds.forEach(couponId -> {
						TiktokCoupon coupon = new TiktokCoupon();
						coupon.setId(couponId);
						coupon.setStartTime(bo.getBeginDate());
						coupon.setEndTime(bo.getEndDate());
						coupon.setTimeType(1);
						couponMapper.updateById(coupon);
					});
				}
			}
		}
		bo.getTags().forEach(t -> {
			activityTagMapper.insert(new TiktokActivityTag().setActivityId(add.getId()).setTagId(t));
		});
		return save;
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = "GetAcitvity", key = "#bo.id")
    public Boolean updateByBo(TiktokActivityBo bo) {
		TiktokActivity update = BeanUtil.toBean(bo, TiktokActivity.class);
        validEntityBeforeSave(bo);
		List<Long> couponIds = bo.getCouponIds();
		boolean b = updateById(update);
		if(b) {
			//删除全部优惠卷
				tiktokActivityToCouponService
					.remove(Wrappers.lambdaQuery(TiktokActivityToCoupon.class)
						.eq(TiktokActivityToCoupon::getActivityId, bo.getId()));
				//添加优惠卷
			if(CollectionUtil.isNotEmpty(couponIds)) {
				couponIds.forEach(couponId -> {
					TiktokActivityToCoupon tiktokActivityToCoupon = new TiktokActivityToCoupon().setActivityId(bo.getId()).setCouponId(couponId);
					tiktokActivityToCouponService.save(tiktokActivityToCoupon);
				});
				if (bo.getIsSynchronizationCoupon() != null && bo.getIsSynchronizationCoupon() == 1) {
					couponIds.forEach(couponId -> {
						TiktokCoupon coupon = new TiktokCoupon();
						coupon.setId(couponId);
						coupon.setStartTime(bo.getBeginDate());
						coupon.setEndTime(bo.getEndDate());
						coupon.setTimeType(1);
						couponMapper.updateById(coupon);
					});
				}
			}
		}
		activityTagMapper.delete(Wrappers.query(new TiktokActivityTag().setActivityId(bo.getId())));
		bo.getTags().forEach(t -> {
			activityTagMapper.insert(new TiktokActivityTag().setActivityId(bo.getId()).setTagId(t));
		});

		return b;
    }



	/**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TiktokActivityBo entity){

		if ( entity.getEndDate().before( entity.getBeginDate())) {
			throw new ServiceException("活动开始时间不能在结束时间后");
		}
		if (entity.getActityType().equals("0") && entity.getCouponIds().isEmpty()) {
			throw new CustomException("优惠卷不能为空");
		}
		if (entity.getEndDate().before(new Date())) {
			throw new ServiceException("活动结束时间不能在当前时间之前");
		}
		if(!SecurityUtils.isManager()){
			entity.setShopId(SecurityUtils.getShop().getId());
		}else{
			if (ObjectUtil.isNull( entity.getShopId())) {
				throw new ServiceException("管理员必须携带指定的shopid");
			}
		}
    }



	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = "GetAcitvity", allEntries=true)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if(isValid){
			if (!SecurityUtils.isManager()) {
				Long id = SecurityUtils.getShop().getId();
				boolean b = list(lambdaQuery().select(TiktokActivity::getShopId).in(TiktokActivity::getId, ids)).stream().allMatch((coupon) -> {
					return coupon.getShopId().equals(id);
				});
				if(!b){
					throw new ServiceException("非法删除");
				}
			}

		}
		ids.forEach(id -> activityTagMapper.delete(Wrappers.query(new TiktokActivityTag().setActivityId(id))));
        return removeByIds(ids);
    }
}
